package cn.daman.chineseol.handler;

import cn.daman.chineseol.entity.Comment;
import cn.daman.chineseol.entity.User;
import cn.daman.chineseol.utils.DataTool;
import cn.daman.chineseol.utils.UserTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.*;

@RestController
@RequestMapping("/cmt")
public class CmtHandler {
    @Autowired
    private DataTool dataTool;
    @Autowired
    private UserTool userTool;
    @GetMapping("/get/{bl}")
    public List<Map<String, Object>> getCmt(@PathVariable Integer bl) {
        List<Comment> cmt = dataTool.cmtRepo.findByBelong(bl);
        List<Map<String, Object>> list = new ArrayList<>();
        for (Comment c : cmt) {
            Map<String, Object> map = new HashMap<>();
            map.put("content", c);
            map.put("u", dataTool.userRepo.findById(c.getUid()).get());
            list.add(map);
        }
        return list;
    }
    @PostMapping("/send")
    public void sendCmt(@RequestBody Comment comment, HttpSession session) {
        User user = userTool.getUser(session);
        comment.setTheTime(new Date());
        comment.setUid(user.getId());
        dataTool.cmtRepo.save(comment);
    }
    @GetMapping("/getMyCmt")
    public List<Comment> getMyCmt(HttpSession session){
        User user = userTool.getUser(session);
        return dataTool.cmtRepo.findByUidOrderByTheTimeDesc(user.getId());
    }
}
